package Utils;

use strict;
use warnings;
use utf8;

use Exporter qw(import);
our @EXPORT = qw(DisplayHash Camel2UnderScore SaveFile RemoveFile);
use File::Path qw(make_path);

sub DisplayHash {
    my ($hash, $indent) = @_;

    # 遍历哈希的键值对
    foreach my $key (keys %$hash) {
        my $value = $hash->{$key};

        # 输出键和值，并在每一级增加缩进
        print "$indent$key: ";

        if (defined $value) {
            if (ref($value) eq 'HASH') {
                # 如果值是哈希，则递归调用函数进行输出
                print "\n";
                DisplayHash($value, $indent . "  ");
            } elsif (ref($value) eq 'ARRAY') {
                # 如果值是列表，则输出列表的所有元素
                print "\n";
                foreach my $item (@$value) {
                    DisplayHash($item, $indent . "  ");
                }
            } else {
                # 否则直接输出值
                print "$value\n";
            }
        } else {
            # 值为 undef，输出 "undef"
            print "undef\n";
        }
    }
}

sub Camel2UnderScore {
    my ($input) = @_;
    if (!defined $input) {
        return '';
    }
    $input =~ s/(?<=[a-z])(?=[A-Z])/_/g;
    $input =~ s/(?<=[A-Z])(?=[A-Z][a-z])/_/g;
    my $result = lc($input);
    return $result;
}

sub SaveFile {
    my ($path, $name, $content) = @_;
    if( !-d $path){
        make_path($path, { mode=>0755 });
    }
    open(my $fh, '>', $path.'/'.$name) or die "无法创建文件";
    print $fh $content;
    close($fh);
}

sub RemoveFile {
    my ($path, $name) = @_;
    my $file = "$path/$name";
    if( -f $file){
        unlink $file or die "无法删除文件";
    }
}

1;
